<%--
  Created by IntelliJ IDEA.
  User: Tsuki
  Date: 2023-07-10
  Time: 15:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <head>
        <title>商品列表</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
        <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/layui.css" media="all">
        <script src="${pageContext.request.contextPath}/static/layui/layui.js" charset="utf-8"></script>
        <script src="${pageContext.request.contextPath}/static/js/showBigImage.js" charset="utf-8"></script>
        <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/public.css" media="all">
    </head>
    <style>
        .layui-table-cell {
            text-align: center;
            height: auto !important;
            white-space: normal;
        }
    </style>
</head>
<body>
<div class="layuimini-container ">
    <div class="layuimini-main">

        <%--  条件搜索框     --%>
        <form class="layui-form layui-row layui-col-space16">
            <div class="layui-col-md2">
                <div class="layui-input-wrap">
                    <div class="layui-input-prefix">
                        <i class="layui-icon layui-icon-username"></i>
                    </div>
                    <input type="text" id="id" value="" placeholder="商品编号" class="layui-input" lay-affix="clear"
                           name="id">
                </div>
            </div>
            <div class="layui-col-md2">
                <div class="layui-input-wrap">
                    <input type="text" id="name" placeholder="商品名称" lay-affix="clear" class="layui-input" name="name">
                </div>
            </div>

            <div class="layui-col-md2">
                <div class="layui-input-wrap">
                    <select  id="category1"   lay-filter="cateGoryName1" class="cateGoryName" lay-affix="clear"  >
                        <option value="-1">一级类别</option>
                    </select>
                </div>
            </div>


            <div class="layui-col-md2">
                <div class="layui-input-wrap">
                    <select name="cateGoryName" lay-filter="cateGoryName2" id="category2"  lay-affix="clear">
                        <option value="">二级类别</option>
                    </select>
                </div>
            </div>

            <div class="layui-col-md2">
                <div class="layui-input-wrap">
                    <select id="shelfState" lay-affix="clear" name="state">
                        <option value="" selected>上架状态</option>
                        <option value="0">未上架</option>
                        <option value="1">已上架</option>
                    </select>
                </div>
            </div>

            <div class="layui-col-md2">
                <div class="layui-btn-container ">
                    <button id="search" class="layui-btn layui-btn-normal layui-row-xs" lay-submit lay-filter="search">
                        查找
                    </button>
                    <button type="reset" class="layui-btn layui-btn-primary layui-row-xs">清空</button>
                </div>
            </div>

        </form>

        <%-- 表头工具条--%>
        <script type="text/html" id="toolbar">
            <div class="layui-btn-container">
                <a class="layui-btn layui-btn-normal layui-btn-sm data-count-edit" lay-event="addGoods">添加商品</a>
                <a class="layui-btn layui-btn-danger layui-btn-sm data-count-edit" lay-event="batchDelist">批量删除</a>
            </div>
        </script>

        <%-- 商品图片列--%>
        <script type="text/html" id="goodsPic">
            <img src="${IMG_SERVER}/goods/{{d.pic}}" onclick="showBigImage(this)" style="width: 100% ; height: 100%"
                 class="goodsPic">
        </script>

        <%-- 上架状态开关按钮--%>
        <script type="text/html" id="shelfStateSwitch">
            <input type="checkbox" name="status" value="{{= d.id }}" title="已上架|已下架" lay-skin="switch"
                   lay-filter="Switch"
                   {{# if (d.state== 1) { }}
                   checked
                   {{# } }}>
        </script>

        <%-- 货物列表--%>
        <table class="layui-hide" id="goodsTable" lay-filter="goodsTableFilter"></table>

        <%-- 行内操作工具条--%>
        <script type="text/html" id="goodsTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-sm data-count-edit" lay-event="view">查看</a>
            <a class="layui-btn layui-btn-danger layui-btn-sm data-count-edit" lay-event="update">修改</a>
        </script>

    </div>
</div>

<script>
    layui.use(['form', 'table', 'element', 'layer'], function (message) {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;
        dropdown = layui.dropdown;

        /**
         * 加载一级类别选择框内容
         */
        $.ajax({
            url: '${pageContext.request.contextPath}/manager/category/list_id_name',
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                // 动态添加新的选项
                $.each(data, function (index, item) {
                    var option = $('<option></option>').val(item.id).text(item.name);
                    $('.cateGoryName').append(option);
                });
                form.render();
            },
            error: function (xhr, textStatus, errorThrown) {
                alert('获取数据失败');
            }
        });

        form.on('select(cateGoryName1)', function(data){
            var elem = data.elem; // 获得 select 原始 DOM 对象
            var value = data.value; // 获得被选中的值
            var othis = data.othis; // 获得 select 元素被替换后的 jQuery 对象
            $.ajax({
                type: 'GET',
                dataType: 'json',
                data:{
                    pid:value,
                },
                url: "${pageContext.request.contextPath}/manager/category/selectIdNameByPid",
                success: function (data) {
                    $("#category2").empty();
                    $.each(data, function (index, item) {
                        $("#category2").append("<option value=" + item.name + ">" + item.name + "</option>");
                    })
                    form.render();
                }
            })
        });

        /**
         * 表格渲染
         */
        table.render({
            elem: '#goodsTable',
            autoSort: true,
            request: {
                pageName: 'pageNum', // 页码的参数名称，默认：page
                limitName: 'pageSize' // 每页数据条数的参数名，默认：limit
            },
            url: '${pageContext.request.contextPath}/manager/goods/list',
            toolbar: '#toolbar',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 100},
                {title: '序号', type: "numbers", width: 80, align: "center"},
                {field: 'id', width: 105, title: '商品编号', sort: true},
                {field: 'name', width: 100, title: '商品名称'},
                {field: 'pic', width: 120, title: '商品主图', align: 'center', templet: "#goodsPic"},
                {
                    field: 'price1', width: 110, title: '市场价格', sort: true, templet: function (d) {
                        return d.price1 + "元"
                    }
                },
                {
                    field: 'price2', width: 110, title: '会员价格', sort: true, templet: function (d) {
                        return d.price2 + "元"
                    }
                },
                {field: 'storage', width: 110, title: '库存数量', sort: true},
                {field: 'unit', width: 100, title: '单位'},
                {field: 'state', width: 120, title: '上架状态', align: 'center', templet: "#shelfStateSwitch", sort: true},
                {
                    title: '操作', minWidth: 150, toolbar: '#goodsTableBar', align: "center"
                }
            ]],
            limits: [4, 15, 20, 25, 50, 100],
            limit: 4,
            page: true,
            initSort: {
                field: 'id', // 按 id 字段排序
                type: 'asc' // 降序排序
            },
            loading: true,
            skin: 'line',
        });

        /**
         * 触发表格复选框选择
         */
        table.on('checkbox(goodsTable)', function (obj) {
            console.log(obj)
        });

        /**
         * 表格头部工具条事件
         */
        table.on('toolbar(goodsTableFilter)', function (obj) {
            if (obj.event === 'addGoods') {
                var index = layer.open({
                    title: '添加商品',
                    type: 2,
                    shade: 0.2,
                    offset: 'lt',
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '${pageContext.request.contextPath}/manager/goods/openAddUpdate',
                    end: function () {
                        table.reload('goodsTable', {}, 'data');
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'batchDelist') {
                var id = obj.config.id;
                var checkStatus = table.checkStatus(id);
                var data = checkStatus.data;
                var selectedIds = [];
                for (var i = 0; i < data.length; i++) {
                    var row = data[i];
                    selectedIds.push(row.id); // 假设id字段为id，你需要将其替换为实际的id字段名
                }
                $.ajax({
                    url: '${pageContext.request.contextPath}/manager/goods/batchDelete',
                    type: 'GET',
                    dataType: 'json',
                    data: {
                        ids: selectedIds.toString(),
                    },
                    success: function (data) {
                        //成功后重载数据
                        table.reload('goodsTable', {}, 'data');
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        alert('获取数据失败');
                    }
                });

            }

        });

        /**
         * 条件搜索表格数据重载
         */
        form.on('submit(search)', function (data) {
            //执行重载
            table.reload('goodsTable', {
                page: {
                    curr: 1 //重新从第 2 页开始
                }
                , where: {
                    id: data.field.id,
                    name: data.field.name,
                    cateGoryName: data.field.cateGoryName,
                    state: data.field.state
                }
            }, 'data');
            return false;
        });

        /**
         * 行内操作按钮事件
         */
        table.on('tool(goodsTableFilter)', function (obj) {
            var data = obj.data;
            /**
             * 查看详情
             */
            if (obj.event === 'view') {
                var viewIndex = layer.open({
                    title: '商品详情',
                    type: 2,
                    shade: 0.2,
                    offset: 'lt',
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '${pageContext.request.contextPath}/manager/goods/details?id=' + data.id,
                });
                $(window).on("resize", function () {
                    layer.full(viewIndex);
                });
            }
            /**
             * 更新商品
             */
            if (obj.event === 'update') {
                var index = layer.open({
                    title: '商品详情',
                    type: 2,
                    shade: 0.2,
                    offset: 'lt',
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '${pageContext.request.contextPath}/manager/goods/openAddUpdate?id=' + data.id,
                    end: function () {
                        table.reload('goodsTable', {}, 'data');
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            }
        });

        /**
         * 上下架状态开关事件
         */
        form.on('switch(Switch)', function (obj) {
            $.ajax({
                url: '${pageContext.request.contextPath}/manager/goods/updateState',
                data: {
                    id: this.value
                },
                type: 'GET',
                success: function () {
                    layer.msg('更新失败')
                },
                error: function (xhr, textStatus, errorThrown) {
                    layer.msg('更新成功')
                }
            });
            layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是 ON|OFF', data.othis)
        });

    });
</script>
</body>
</html>
